<?php

namespace app\service;

use app\model\ImUserModel;
use app\model\RoleModel;
use app\model\TenantApplyModel;
use app\model\TenantGrantModel;
use app\model\TenantUserModel;
use app\tool\SingletonTrait;

class OverviewService
{
    use SingletonTrait;

    /**
     * 企业概览统计
     * @param $tenantId
     * @return array|int[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function statistics($tenantId)
    {
        if (empty($tenantId)) {
            return [
                'user_total' => 0,
                'apply_user_total' => 0,
                'grant_total' => 0,
                'admin_total' => 0
            ];
        }

        // 1. 组织总人数
        $tenantUserTotal = TenantUserModel::join("im_user user", "user.id = tenant_user.user_id")
            ->where(['tenant_user.tenant_id' => $tenantId, 'user.is_system' => 'no', 'user.active' => ImUserModel::ACTIVE_ENABLE])
            ->count();

        // 2. 申请中人数
        $applyToTenantUserTotal = TenantApplyModel::where(['tenant_id' => $tenantId, 'status' => TenantApplyModel::STATUS_IN_REVIEW])->count();
        // 3. 授权人数
        $tenantGrantTotal = TenantGrantModel::where(['tenant_id' => $tenantId])->count();
        // 获取租户管理员角色id
        $adminInfo = RoleModel::where(['code' => RoleModel::TENANT_ADMINISTRATOR_CODE])->field('id')->find();
        // 4. 租户管理员人数
        $adminTotal = 0;
        if (!empty($adminInfo['id'])) {
            $adminTotal = TenantUserModel::join("tenant_user_role", "tenant_user.id = tenant_user_role.tenant_user_id")
                ->where(['tenant_user.tenant_id' => $tenantId, 'tenant_user_role.role_id' => $adminInfo['id']])
                ->count();
        }

        return [
            'user_total' => $tenantUserTotal,
            'apply_user_total' => $applyToTenantUserTotal,
            'grant_total' => $tenantGrantTotal,
            'admin_total' => $adminTotal
        ];
    }
}